! function() {
    // 引入qrcode核心库
    var qrcode = require('./qrcode.js').api;

    /**
     * 二维码生成器类
     * 不依赖painter和wx-canvas组件
     */
    var QRCodeHelper = function() {
        this.canvasWidth = 300;
        this.canvasHeight = 300;
        this.eccLevel = 2; // 默认纠错级别
    };

    /**
     * 设置二维码大小
     * @param {number} width - 宽度
     * @param {number} height - 高度
     */
    QRCodeHelper.prototype.setSize = function(width, height) {
        this.canvasWidth = width;
        this.canvasHeight = height;
    };

    /**
     * 设置纠错级别
     * @param {number} level - 纠错级别(0-3)
     */
    QRCodeHelper.prototype.setEccLevel = function(level) {
        this.eccLevel = level;
        qrcode.ecclevel = level;
    };

    /**
     * 生成二维码数据
     * @param {string} text - 要编码的文本
     * @returns {Array} 二维码数据数组
     */
    QRCodeHelper.prototype.generateQRCode = function(text) {
        qrcode.ecclevel = this.eccLevel;
        return qrcode.getFrame(text);
    };

    /**
     * 绘制二维码到Canvas
     * @param {Object} canvasContext - Canvas上下文
     * @param {string} text - 要编码的文本
     * @param {Object} options - 选项
     * @returns {Promise} 绘制完成的Promise
     */
    QRCodeHelper.prototype.drawQRCode = function(canvasContext, text, options) {
        options = options || {};
        this.setEccLevel(options.eccLevel || this.eccLevel);
        this.setSize(options.width || this.canvasWidth, options.height || this.canvasHeight);

        var qrData = this.generateQRCode(text);
        var moduleCount = qrcode.size;
        var moduleSize = Math.min(this.canvasWidth / moduleCount, this.canvasHeight / moduleCount);

        return new Promise((resolve, reject) => {
            try {
                // 清除画布
                canvasContext.clearRect(0, 0, this.canvasWidth, this.canvasHeight);

                // 设置背景
                if (options.backgroundColor) {
                    canvasContext.fillStyle = options.backgroundColor;
                    canvasContext.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
                }

                // 绘制二维码
                canvasContext.fillStyle = options.color || 'black';
                for (var row = 0; row < moduleCount; row++) {
                    for (var col = 0; col < moduleCount; col++) {
                        if (qrData[col * moduleCount + row]) {
                            canvasContext.fillRect(
                                col * moduleSize,
                                row * moduleSize,
                                moduleSize,
                                moduleSize
                            );
                        }
                    }
                }

                resolve();
            } catch (error) {
                reject(error);
            }
        });
    };

    /**
     * 生成二维码URL
     * @param {string} text - 要编码的文本
     * @param {Object} options - 选项
     * @returns {Promise} 包含二维码URL的Promise
     */
    QRCodeHelper.prototype.generateQRCodeUrl = function(text, options) {
        options = options || {};
        const width = options.width || this.canvasWidth;
        const height = options.height || this.canvasHeight;

        return new Promise((resolve, reject) => {
            try {
                // 在小程序环境中创建Canvas上下文
                const query = wx.createSelectorQuery();
                query.select('#temp-qrcode-canvas')
                    .fields({ node: true, size: true })
                    .exec((res) => {
                        if (!res || !res[0]) {
                            console.error('获取Canvas节点失败', res);
                            reject('获取Canvas节点失败');
                            return;
                        }

                        const canvasNode = res[0].node;
                        const ctx = canvasNode.getContext('2d');

                        if (!ctx) {
                            console.error('获取Canvas上下文失败');
                            reject('获取Canvas上下文失败');
                            return;
                        }

                        // 设置Canvas大小
                        canvasNode.width = width;
                        canvasNode.height = height;

                        // 绘制二维码
                        this.drawQRCode(ctx, text, options)
                            .then(() => {
                                // 转换为临时文件路径
                                wx.canvasToTempFilePath({
                                    canvas: canvasNode,
                                    width: width,
                                    height: height,
                                    destWidth: width,
                                    destHeight: height,
                                    success: (res) => {
                                        console.log('二维码生成成功', res.tempFilePath);
                                        resolve(res.tempFilePath);
                                    },
                                    fail: (error) => {
                                        console.error('canvasToTempFilePath失败', error);
                                        reject(error);
                                    }
                                });
                            })
                            .catch((error) => {
                                console.error('drawQRCode失败', error);
                                reject(error);
                            });
                    });
            } catch (error) {
                console.error('generateQRCodeUrl异常', error);
                reject(error);
            }
        });
    };

    // 导出模块
    module.exports = {
        default: QRCodeHelper
    };
}();